/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-01 08:55:36
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-02 11:09:36
 */
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'

import styles from './index.module.scss'
/* 导入store中的action/loginAction */
import { loginAction } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'

/* dispatch */
import { useDispatch } from 'react-redux'

/* 类型申明文件 */
import { LoginForm } from '@/types/data'
import { AxiosError } from 'axios'

import { useRef } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'

import { getCode } from '@/store/actions/login'

/* hooks */
import { useCountDown } from '@/hooks/useCountDown'

const Login = () => {
  /* hooks */
  const callback = () => {
    console.log('callback');

  }
  const { start, count } = useCountDown(callback)
  const [form] = Form.useForm()   // mobile组件库给定的API 
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(loginAction(values))
      Toast.show({
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          // 返回首页
          history.replace('/')
        },
      })
    } catch (e) {
      /* 类型断言 */
      const error = e as AxiosError<{ message: string }>
      console.dir(error.message)
      // alert(error.message)
    }
    // console.log(values, 11)

  }

  const mobileRef = useRef<InputRef>(null)

  /* 验证码 */
  const sendCode = async () => {
    // 拿到手机号
    const mobile = form.getFieldValue('mobile')
    console.log(mobile, 77);
    // 判断手机号校验是否成功
    const hasError = form.getFieldError('mobile').length > 0  //  不满足会返回true
    console.log(hasError, 66);
    // 校验
    if (!mobile || hasError) {
      //判断是不是有值，以及校验规则是否满足
      // 手机号码对应文本框 DOM 元素
      const mobileInputDOM = mobileRef.current
      console.log(mobileInputDOM, 8811);

      // focus() 就是用来获得焦点的一个方法，是 DOM 元素自己提供的
      mobileInputDOM?.focus()
      return
    }
    // 开启定时器
    start(5)

    try {
      await dispatch(getCode(mobile))
      Toast.show({ content: '短信已发送' })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }

  }

  const initialValues: LoginForm = {
    mobile: "13800000003",
    code: "246810"
  }

  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form initialValues={initialValues} form={form} onFinish={onFinish}>
          <Form.Item className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]}>
            <Input placeholder="请输入手机号" ref={mobileRef} />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span onClick={sendCode} className="code-extra">=={count}=={count > 1 ? count + 's之后获取' : '发送验证码'}</span>}
          >
            <Form.Item className="login-item"
              name="code"
              rules={[{ required: true, message: '请输入验证码' }]}>
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login